import axios from 'axios'
import type { AxiosInstance, AxiosError } from 'axios'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API || '/api', // 从环境变量获取基础URL
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加token等认证信息
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error: AxiosError) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    
    // 这里可以根据后端返回的状态码进行处理
    // 假设后端返回的格式为 { code: number, message: string, data: any }
    if (res.code && res.code !== 200) {
      console.error('请求失败:', res.message || '未知错误')
      return Promise.reject(new Error(res.message || '未知错误'))
    }
    
    return res
  },
  (error: AxiosError) => {
    console.error('响应错误:', error)
    return Promise.reject(error)
  }
)

// 导航相关API
export const navApi = {
  // 获取分类列表
  getCategories: () => service.get('/nav/categories'),
  
  // 获取二级分类列表
  getSubCategories: (categoryId: string) => service.get(`/nav/subcategories/${categoryId}`),
  
  // 获取导航项列表
  getNavItems: (params?: {
    categoryId?: string
    subCategoryId?: string
    keyword?: string
  }) => service.get('/nav/items', { params }),
  
  // 搜索导航项
  searchNavItems: (keyword: string) => service.get('/nav/search', { params: { keyword } }),
  
  // 获取导航项详情
  getNavItemDetail: (id: string) => service.get(`/nav/items/${id}`)
}

// 用户相关API
export const userApi = {
  // 登录
  login: (data: any) => service.post('/auth/login', data),
  // 注册
  register: (data: any) => service.post('/auth/register', data),
  // 获取用户信息
  getUserInfo: () => service.get('/system/user/profile'),
  // 更新用户信息
  updateUserInfo: (data: any) => service.put('/system/user/profile', data),
  // 修改密码
  changePassword: (data: any) => service.put('/system/user/profile/updatePwd', data),
  // 登出
  logout: () => service.post('/auth/logout')
}

// 导出单独的函数
export const login = (data: any) => service.post('/auth/login', data)
export const register = (data: any) => service.post('/auth/register', data)
export const getUserInfo = () => service.get('/system/user/profile')
export const updateUserInfo = (data: any) => service.put('/system/user/profile', data)
export const changePassword = (data: any) => service.put('/system/user/profile/updatePwd', data)
export const logout = () => service.post('/auth/logout')
export const getCodeImg = () => service.get('/captchaImage')

// 重新导出login相关的API，保持兼容性
export * from './login';
// 暂时注释掉对types.ts的重新导出，避免导入问题
// export * from './types';

// 导出nav相关的API
export * from './nav/ncategory';
  export * from './nav/project';
  // 已在各模块内定义类型，移除重复的重新导出
  export * from './nav/categoryProject';

export default service
